import React, { Component } from 'react'
import axios from 'axios'
import PropTypes from 'prop-types'
import PubSub from 'pubsub-js'

export default class Search extends Component {
  static propTypes = {
    updateAppState: PropTypes.func.isRequired,
  }
  
  search = () => {
    // 获取用户的输入
    const {keywordElement: {value}} = this
    // 发送请求前通知app更新状态
    PubSub.publish('atguigu', {isFirst: false, isLoading: true})
    // this.props.updateAppState({
    //   isFirst: false,
    //   isLoading: true,
    // })
    // 发送网络请求
    axios.get(`http://api.github.com/search/users?q=${value}`).then(
      res => {
        // avatar_url  login html-url
        console.log('成功', res)
        // this.props.updateAppState({
        //   isLoading: false,
        //   users: res.data.items || [],
        // })

        // 请求成功后通知List更新状态
        PubSub.publish('atguigu', {isLoading: false, users: res.data.items || []})
      },
      err => {
        // 请求失败后通知app更新状态
        // this.props.updateAppState({
        //   isLoading: false,
        //   err,
        // })
        console.log('失败', err)
        PubSub.publish('atguigu', {isLoading: false, err: err.message})
      }
    )
  }
  render() {
    return (
      <div>
        <section className="jumbotron">
          <h3 className="jumbotron-heading">Search Github Users</h3>
          <div>
            {/* 回调函数形式获取ref */}
            <input ref={c => this.keywordElement = c} type="text" placeholder="输入关键词点击搜索" />&nbsp;
            <button onClick={this.search}>Search</button>
          </div>
        </section>
      </div>
    )
  }
}
